import { betterAuth } from 'better-auth';
import { username, admin } from 'better-auth/plugins';
import { drizzle } from 'drizzle-orm/d1';
import { Bindings } from '../bindings';

export type Auth = ReturnType<typeof betterAuth>;

let auth: Auth;

export const initAuth = (env: Bindings) => {
  if (!auth) {
    const db = drizzle(env.D1DATA);
    auth = betterAuth({
      database: {
        db,
        type: 'sqlite',
      },
      secret: env.BETTER_AUTH_SECRET,
      // baseURL: process.env.BETTER_AUTH_URL,
      emailAndPassword: {
        enabled: true,
      },
      socialProviders: {
        github: {
          clientId: process.env.GITHUB_CLIENT_ID as string,
          clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
        },
      },
      plugins: [username(), admin()],
    });
  }
  return auth;
};
